package gw.com.android.ui.bulletin;

import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.gts2.hx.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;
import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.ConfigSettingDeal;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.terminal.GTSDataListener;
import gw.com.android.ui.BaseActivity;
import gw.com.android.utils.PackStatis;
import gw.com.android.utils.ThreadPool;
import gw.com.jni.library.terminal.GTSConst;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import www.com.library.app.Logger;
import www.com.library.model.DataItemDetail;
import www.com.library.util.CommonUtils;
import www.com.library.util.DoubleConverter;
import www.com.library.util.StringFormatter;
import www.com.library.util.StringUtils;
import www.com.library.view.BtnClickListener;

/**
 * 消息详情
 *
 * @author reeta
 *
 */
public class BulletinDetailActivity extends BaseActivity {

	@BindView(R.id.ll_content)
	View mContentLayout;
	@BindView(R.id.news_subject)
	TextView mTitleSubView;
	@BindView(R.id.news_time)
	TextView mTitleTimeView;
	@BindView(R.id.loading_progress_view)
	View mProgressView;
	@BindView(R.id.webview)
	WebView mWebView;
	@BindView(R.id.error_layout)
	View mErrorView;
	private String mTitle;
	private int mDataId;
	private String type;
	private String url;
	private int formType = AppContances.TYPE_FORM_BULLETIN;//标识从哪个界面过来，默认从消息中心过来
	private Thread mThread;
	private final int NEWS_DETAIL = 1;
	private final int URL_NEWS_DETAIL = 2;
	private int pageType = NEWS_DETAIL;
	private ConfigSettingDeal mSettingDeal;
	private int mSeq = 0;

	@Override
	protected int getLayoutView() {
		return R.layout.activity_message_detail;
	}

	@Override
	protected void initLayoutView() {
		mTitle = getIntent().getStringExtra("title");
		mDataId = getIntent().getIntExtra("mDataId",0);
		type = getIntent().getStringExtra("type");
		url = getIntent().getStringExtra("url");
		Logger.e("消息详情界面接收到的数据：" + mDataId +", " + type);
		formType = getIntent().getIntExtra("fromType", AppContances.TYPE_FORM_BULLETIN);
		mTitle = AppMain.getAppString(R.string.system_notice_detail);
		mTitleBar.setAppTitle(mTitle);
		mTitleBar.setBtnClickListener(new BtnClickListener() {
			@Override
			public void onBtnClick(int viewID) {
				if(viewID == R.id.title_left_icon){
					if (mWebView.canGoBack()) {
						mWebView.goBack();// 返回前一个页面
					}else{
						goBack();
					}

				}
			}
		});
	}

	@Override
	protected void initViewData() {
		mSettingDeal = new ConfigSettingDeal();
		mProgressView.setVisibility(View.VISIBLE);
		mContentLayout.setVisibility(View.GONE);
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.getSettings().setDefaultTextEncodingName("utf-8");
		mWebView.setBackgroundColor(0); // 设置背景色
		mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
		mWebView.getSettings().setUseWideViewPort(true);
		mWebView.getSettings().setDomStorageEnabled(true);
		mWebView.getSettings().setLoadWithOverviewMode(true);
		mWebView.setWebChromeClient(new ReWebChomeClient());
		mWebView.setWebViewClient(new webViewClient());
		loadData();
	}

	/**
	 * 加载数据
	 */
	private void loadData(){
        ThreadPool.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                Logger.e("bulletindetail线程id = " + android.os.Process.myTid());
                String language = getIntent().getStringExtra("language");
                if (null == language || language.isEmpty()) {
                    language = GTConfig.instance().getLanguage();
                }
                Logger.e("language = " + language);
                AppTerminal.instance().setNewsMarkRead(AppContances.MARK_BULLENTIN_TYPE, AppContances.BULLENTIN_TYPE_ALL + "", mDataId);
                mSeq = GTSDataListener.curSeq++;
                AppTerminal.instance().getBulletinDetail(mDataId, language, mSeq);
            }
        });
	}

	@Override
	public void onDetachedFromWindow() {
		super.onDetachedFromWindow();
		mWebView.destroy();
	}

	/**
	 * 返回到上级界面
	 */
	private void goBack(){
		this.finish();
//		if(formType == AppContances.BULLETIN_TYPE_FORM_BULLETIN){
//			BulletinDetailActivity.this.finish();
//		}else{
//			ActivityManager.showBulletinActivity(BulletinDetailActivity.this, AppMain.getAppString(R.string.system_bulletin));
//			BulletinDetailActivity.this.finish();
//		}
	}

	@OnClick(R.id.error_layout)
	public void errorClick(){
		if(CommonUtils.isFastDoubleClick()){
			return;
		}
		if(null != mErrorView){
			mErrorView.setVisibility(View.GONE);
		}
		if(null != mProgressView){
			mProgressView.setVisibility(View.VISIBLE);
		}
		loadData();
	}

	/**
	 * 失败处理
	 * @param errorMessage
     */
	private void failDeal(String errorMessage){
		mProgressView.setVisibility(View.GONE);
		mContentLayout.setVisibility(View.GONE);
		mErrorView.setVisibility(View.VISIBLE);
		showToastPopWindow(errorMessage);
	}

	@Override
	public void registerRxBus() {
		super.registerRxBus();
		Disposable getMobileRegister = RxBus.getInstance().register(GTSConst.REPLY_HTTP_NOTIFY_DETAIL+"", Bundle.class).observeOn(AndroidSchedulers.mainThread())
				.subscribe(new Consumer<Bundle>(){

					@Override
					public void accept(@io.reactivex.annotations.NonNull Bundle bundle) throws Exception {
						int iValue = bundle.getInt("iValue");
						Logger.e("消息详情数据返回成功 iValue = " + iValue  +", mseq = " + bundle.getInt("iNotification"));
						if(bundle.getInt("iNotification") != mSeq){
							return;
						}

						if(iValue != 0 ){
							failDeal(ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1012));
							return;
						}

						if(null != bundle){
							String strObject = bundle.getString("strObject");
							try {
								JSONObject object = new JSONObject(strObject);
								JSONArray jsonArray = object.optJSONArray("data");
								if(null != jsonArray && jsonArray.length() > 0){
									url = jsonArray.optJSONObject(0).getString("url");
									if(!StringUtils.isEmpty(url)){
										pageType = URL_NEWS_DETAIL;
										if(null != url && !url.startsWith("http")){
											url ="http://" +url;
										}
										mContentLayout.setVisibility(View.GONE);
										mWebView.loadUrl(url);
									}else {
										if(mDataId == jsonArray.optJSONObject(0).optInt("dataid")){
											pageType = NEWS_DETAIL;
											Logger.e("消息详情数据返回成功2");
											mProgressView.setVisibility(View.GONE);
											mErrorView.setVisibility(View.GONE);
											mContentLayout.setVisibility(View.VISIBLE);
											mTitleSubView.setText(jsonArray.optJSONObject(0).optString("title"));
											String updatetime = jsonArray.optJSONObject(0).optString("createtimestamp");
											if("".equals(updatetime)){
												mTitleTimeView.setText(jsonArray.optJSONObject(0).optString("createtime"));
											}else{
												mTitleTimeView.setText(StringFormatter.instance().secToDateTime(DoubleConverter.toLongData(updatetime)/1000));
											}
											// 加载HTML字符串进行显示
//										String html = "<html><head><meta name='viewport' content='width=device-width, initial-scale=1.0' /></head><body>"
//												+ "<div style='font-size:15px;color:#404040;line-height:160%;word-break:break-all'>"
//												+ jsonArray.optJSONObject(0).optString("content") + "</div></body><html>";
											StringBuffer htmlbuf =  new StringBuffer();
											htmlbuf.append("<html><head><meta name='viewport' content='width=device-width, initial-scale=1.0' />");
											htmlbuf.append("<style type='text/css'>");
											htmlbuf.append("img {height: auto;position: relative;width: 100%;}");
											htmlbuf.append("</style>");
											htmlbuf.append("</head>");
											htmlbuf.append("<body>");
											htmlbuf.append("<div style='font-size:15px;color:#404040;line-height:160%;word-break:break-all'>");
											htmlbuf.append(jsonArray.optJSONObject(0).optString("content"));
											htmlbuf.append("</div></body><html>");

											if (null != mWebView) {
												mWebView.loadDataWithBaseURL(null, htmlbuf.toString(), "text/html", "utf-8", null);
											}
										}else{
											failDeal(ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1012));
										}
									}

								}else{
									failDeal(ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1012));
								}

							} catch (JSONException e) {
								failDeal(ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1012));
								e.printStackTrace();
							}
						}else{
							failDeal(ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1012));
						}
					}
				});

		bindSubscription(getMobileRegister);
	}

	class webViewClient extends WebViewClient {

		//重写shouldOverrideUrlLoading方法，使点击链接后不使用其他的浏览器打开。
		@Override

		public boolean shouldOverrideUrlLoading(WebView view, String mUrl) {

			if(pageType == NEWS_DETAIL){
				DataItemDetail item = mSettingDeal.getItemValue(AppMain.getAppString(R.string.system_notice_detail), mUrl);
				item.setBooleanValue(ConfigType.CONFIG_TYPE_TYPE_HASBACK_TAG, true);
				ActivityManager.showWebPageActivity(BulletinDetailActivity.this, item, AppMain.getAppString(R.string.btn_back));
			}else{
				mWebView.loadUrl(mUrl);
				PackStatis.getToService(PackStatis.EventAction.CLICKMESSAGELINK.getValue(),PackStatis.EventCategory.MESSAGE.getValue(),null,null);
			}
			//如果不需要其他对点击链接事件的处理返回true，否则返回false

			return true;
		}

	}

	public class ReWebChomeClient extends WebChromeClient {

		@Override
		public void onReceivedTitle(WebView view, String title) {
			super.onReceivedTitle(view, title);
			Log.d("ANDROID_LAB", "TITLE=" + title);
			/*if(view.canGoBack()){
				mTitleBar.setLeftResource(R.string.btn_back);
			}else{
				mTitleBar.setLeftResource(R.string.system_bulletin);
			}*/

		}
		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			if (newProgress == 100) {
				mProgressView.setVisibility(View.GONE);
			}else{
				mProgressView.setVisibility(View.VISIBLE);
			}
			super.onProgressChanged(view, newProgress);
		}
	}
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
			mWebView.goBack();// 返回前一个页面
//			goBack();
			return true;
		}

		return super.onKeyUp(keyCode, event);
	}
}
